/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.kasoft.emq.controller;

import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.pig4cloud.pigx.common.core.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename;


/**
 *
 *
 * @author
 * @date
 */
@RestController
@AllArgsConstructor
@RequestMapping("/device" )
@Api(value = "device", tags = "用户信息")
@Slf4j
public class EmqDeviceController {

	@Autowired
	private GridFsTemplate gridFsTemplate;

	@Resource
	GridFsOperations gridOperations;

	@ApiOperation(value = "通过文件名查询", notes = "通过文件名查询心电图")
	@GetMapping("/{fileName}" )
    public R findFilesInGridFs(@PathVariable String fileName) throws IOException {
     	GridFSFindIterable result = gridFsTemplate.find(query(whereFilename().is(fileName)));
		GridFSFile tResult = result.first();
		GridFsResource[] txtFiles = gridFsTemplate.getResources(tResult.getFilename());
		GridFsResource txtFile = txtFiles[0];
			InputStream in = txtFile.getInputStream();
			byte[] tt = new byte[1024];
			int b;
			while ((b = in.read(tt)) != -1) {
				String tzt = new String(tt, "utf-8");
				return R.ok(tzt);
			}
		return R.ok();
	}

}
